package org.alis.ap.rpc.server.manager;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.alis.ap.rpc.Request;
import org.alis.ap.rpc.ServiceDescriptor;
import org.alis.ap.rpc.server.ServiceInstance;
import org.alis.ap.rpc.utils.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * ServiceManager desc:
 * 管理rpc 暴露的服务
 *
 * @author luochuan
 * @date 2020/10/16 17:00
 */
@Slf4j
public class ServiceManager {
    private Map<ServiceDescriptor, ServiceInstance> serviceInstanceMap;

    public ServiceManager() {
        this.serviceInstanceMap = Maps.newConcurrentMap();
    }

    public void register(Class<?> interfaceClass, Object bean) {
        for (Method method : ReflectionUtils.getPublicMethod(interfaceClass)) {
            serviceInstanceMap.put(ServiceDescriptor.from(interfaceClass, method), new ServiceInstance(bean, method));
            log.info("注册成功,{},{}", interfaceClass.getSimpleName(), method.getName());
        }
    }

    public ServiceInstance lookup(Request request) {
        return serviceInstanceMap.get(request.getServiceDescriptor());

    }
}
